const { classApi } = require('../../../utils/api');

Page({
  data: {
    classId: null,
    classInfo: null,
    loading: false,
    error: null
  },

  onLoad(options) {
    console.log('根据用户classId查找班级页面加载，参数:', options);
    
    const { classId } = options;
    if (!classId) {
      wx.showToast({
        title: '班级ID不能为空',
        icon: 'none'
      });
      wx.navigateBack();
      return;
    }
    
    this.setData({
      classId: parseInt(classId)
    });
    
    this.loadClassInfo();
  },

  // 加载班级信息
  async loadClassInfo() {
    this.setData({ loading: true, error: null });
    
    try {
      console.log('开始加载班级信息，班级ID:', this.data.classId);
      
      const result = await classApi.getClassByClassId(this.data.classId);
      console.log('班级信息获取成功:', result);
      
      if (result && result.data) {
        this.setData({
          classInfo: result.data,
          loading: false
        });
      } else {
        throw new Error('获取班级信息失败');
      }
      
    } catch (error) {
      console.error('获取班级信息失败:', error);
      this.setData({
        error: '加载失败，请重试',
        loading: false
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 复制班级邀请码
  copyClassCode() {
    if (this.data.classInfo && this.data.classInfo.classCode) {
      wx.setClipboardData({
        data: this.data.classInfo.classCode,
        success: () => {
          wx.showToast({
            title: '邀请码已复制',
            icon: 'success'
          });
        }
      });
    }
  },

  // 查看班级成员
  viewClassMembers() {
    if (this.data.classInfo) {
      wx.navigateTo({
        url: `/pages/class/class-members/index?classId=${this.data.classInfo.classId}&className=${encodeURIComponent(this.data.classInfo.className)}`
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadClassInfo().then(() => {
      wx.stopPullDownRefresh();
    });
  }
});
